/*
 * =====================================================================================
 *
 *       Filename:  cl_timestamp.cxx
 *
 *    Description:  
 *
 *        Version:  1.0
 *        Created:  02/27/2011 03:07:20 PM
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  Ken Chen (Ken), chen_kenz@emc.com
 *        Company:  EMC
 *
 * =====================================================================================
 */

#include <cstddef>
#include <sstream>
#include "cl_timestamp.hxx"

namespace neo
{
using namespace std;

CLTimestamp::CLTimestamp(int secs, int msecs) 
{
  m_timeStamp.tv_sec = secs; 
  m_timeStamp.tv_usec = msecs;
}

bool CLTimestamp::operator>(const CLTimestamp& other) const 
{
  if(m_timeStamp.tv_sec > other.m_timeStamp.tv_sec)
  {
    return true;
  }
  else if(m_timeStamp.tv_sec == other.m_timeStamp.tv_sec)
  {
    if(m_timeStamp.tv_usec > other.m_timeStamp.tv_usec)
    {
      return true;
    }
    return false;
  }
  else
  {
    return false;
  }
}

bool CLTimestamp::operator==(const CLTimestamp& other) const 
{
  return (m_timeStamp.tv_sec == other.m_timeStamp.tv_sec) &&
         (m_timeStamp.tv_usec == other.m_timeStamp.tv_usec);
}

bool CLTimestamp::operator<(const CLTimestamp& other) const 
{
  if(operator==(other))
  {
    return false;
  }
  else
  {
    return !operator>(other);
  }
}

CLTimestamp& CLTimestamp::operator+=(int msecs) 
{
  m_timeStamp.tv_sec += msecs/MICROSECOND_PER_SECOND;
  m_timeStamp.tv_usec += msecs%MICROSECOND_PER_SECOND;
  return *this;
}

const CLTimestamp CLTimestamp::operator+(int msecs) const 
{
  CLTimestamp ts(*this);
  return (ts+=msecs);
}

const CLTimestamp CLTimestamp::nowTime(void) 
{
  struct timeval tv;
  if(gettimeofday(&tv, NULL) < 0)
  {
    return CLTimestamp::nullTime();
  }
  return CLTimestamp(tv.tv_sec, tv.tv_usec); 
}

const CLTimestamp CLTimestamp::nullTime(void) 
{
  static CLTimestamp nilTime;
  return nilTime;
}

void CLTimestamp::getTime(int& secs, int& msecs) const
{
  secs = m_timeStamp.tv_sec;
  msecs = m_timeStamp.tv_usec;
}

const string CLTimestamp::toString(void) const
{
  stringstream ss;
  ss << "Secs: " << m_timeStamp.tv_sec << " " << "MSecs: " << m_timeStamp.tv_usec;
  return ss.str();
}

const string CLTimestamp::toFormatString(void) const 
{
  time_t tnow = m_timeStamp.tv_sec;
  struct tm tim;
  localtime_r(&tnow, &tim);
  char buf[32] = {'\0'};
  int n = snprintf(buf, sizeof(buf), "%04d-%02d-%02d %02d:%02d:%02d.%06d",
                                     tim.tm_year + 1900,
                                     tim.tm_mon + 1,
                                     tim.tm_mday,
                                     tim.tm_hour,
                                     tim.tm_min,
                                     tim.tm_sec,
                                     (int)m_timeStamp.tv_usec);
  (void)n;
  return buf;
}

} //neo
